package com.dingding.gmall.order.controller;

import com.dingding.gmall.common.exception.NoStockException;
import com.dingding.gmall.order.command.SubmitOrderCommand;
import com.dingding.gmall.order.dto.FareInfoDTO;
import com.dingding.gmall.order.service.OrderService;
import com.dingding.gmall.order.vo.OrderTradeVO;
import com.dingding.gmall.order.vo.SubmitOrderResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author liugongding
 * @description: 订单结算
 * @date 2022/2/24 11:22 PM
 */

@Slf4j
@Controller
public class OrderTradeController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderTradeVO orderTradeVO = orderService.tradeOrder();
        model.addAttribute("orderTradeData", orderTradeVO);
        return "trade";
    }

    @GetMapping("/fare")
    @ResponseBody
    public FareInfoDTO getFare(@RequestParam("addressId")Long addressId){
        return orderService.getFare(addressId);
    }

    @PostMapping("/submitOrder")
    public String submitOrder(SubmitOrderCommand command, Model model, RedirectAttributes attributes) {
        try {
            SubmitOrderResponseVO response = orderService.submitOrder(command);
            if (response.getCode() == 0) {
                model.addAttribute("response", response);
                return "pay";
            } else {
                String msg = "下单失败";
                switch (response.getCode()) {
                    case 1: msg += "令牌订单信息过期，请刷新再次提交"; break;
                    case 2: msg += "库存锁定失败，商品库存不足"; break;
                }
                attributes.addFlashAttribute("msg",msg);
                log.error(msg);
                return "redirect:http://127.0.0.1:9000/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String message = e.getMessage();
                attributes.addFlashAttribute("msg",message);
            }
            return "redirect:http://127.0.0.1:9000/toTrade";
        }
    }
}
